package LeetCode;

public class LivelockExample {
    private boolean turn = true; // 用于控制谦让的标志

    public void sendMessages() {
        Thread t1 = new Thread(() -> {
            while (true) {
                synchronized (this) {
                    if (turn) { // 如果轮到对方发送消息
                        System.out.println("Thread 1: It's your turn, I'll wait.");
                        turn = false; // 让对方发送消息
                        this.notify(); // 唤醒对方
                        try {
                            this.wait(); // 等待对方发送消息
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        System.out.println("Thread 1: Sending message.");
                        turn = true; // 完成发送，让对方发送消息
                        this.notify(); // 唤醒对方
                        break; // 完成任务，退出循环
                    }
                }
            }
        });

        Thread t2 = new Thread(() -> {
            while (true) {
                synchronized (this) {
                    if (!turn) { // 如果轮到对方发送消息
                        System.out.println("Thread 2: It's your turn, I'll wait.");
                        turn = true; // 让对方发送消息
                        this.notify(); // 唤醒对方
                        try {
                            this.wait(); // 等待对方发送消息
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        System.out.println("Thread 2: Sending message.");
                        turn = false; // 完成发送，让对方发送消息
                        this.notify(); // 唤醒对方
                        break; // 完成任务，退出循环
                    }
                }
            }
        });

        t1.start();
        t2.start();
    }

    public static void main(String[] args) {
        LivelockExample example = new LivelockExample();
        example.sendMessages();
    }
}